#!/usr/bin/env python
# vim:fileencoding=utf-8
# from datetime import datetime, timedelta

# from calibre.utils.date import parse_date
from calibre.web.feeds.news import BasicNewsRecipe, classes


class IndianExpress(BasicNewsRecipe):
    title = 'Indian Express'
    language = 'en_IN'
    __author__ = 'unkn0wn'
    oldest_article = 1.15  # days
    encoding = 'utf-8'
    masthead_url = 'https://indianexpress.com/wp-content/themes/indianexpress/images/indian-express-logo-n.svg'
    no_stylesheets = True
    use_embedded_content = False
    remove_attributes = ['style', 'height', 'width']
    ignore_duplicate_articles = {'url'}

    extra_css = '''
        .ie-custom-caption, .custom-caption, .ie-authorbox, .author-block, #storycenterbyline .top-opinion { font-size:small; }
        blockquote { color:#404040; }
        em, #sub-d, .top-description { color:#202020; font-style:italic; }
        img { display:block; margin:0 auto; }
    '''

    resolve_internal_links = True
    remove_empty_feeds = True

    keep_only_tags = [
        classes(
            'heading-part full-details top-opinion article-main-head top-description top-image-part story_details'
        )
    ]
    remove_tags = [
        dict(name='div', attrs={'id': 'ie_story_comments'}),
        dict(name='div', attrs={'class': lambda x: x and 'related-widget' in x}),
        dict(name='img', attrs={'src': lambda x: x and x.endswith('-button-300-ie.jpeg')}),
        dict(name='a', attrs={'href': lambda x: x and x.endswith('/?utm_source=newbanner')}),
        classes(
            'share-social appstext ie-int-campign-ad ie-breadcrumb custom_read_button unitimg copyright '
            'storytags pdsc-related-modify news-guard premium-story append_social_share ie-int-campign-ad '
            'digital-subscriber-only h-text-widget ie-premium ie-first-publish adboxtop adsizes immigrationimg '
            'next-story-wrap ie-ie-share next-story-box brand-logo quote_section ie-customshare osv-ad-class '
            'custom-share o-story-paper-quite ie-network-commenting audio-player-tts-sec o-story-list subscriber_hide '
            'author-social author-follow author-img premium_widget_below_article author-block'
        )
    ]

    recipe_specific_options = {
        'days': {
            'short': 'Oldest article to download from this news source. In days ',
            'long': 'For example, 0.5, gives you articles from the past 12 hours',
            'default': str(oldest_article),
        },
        'res': {
            'short': 'For hi-res images, select a resolution from the\nfollowing options: 400, 800, 1200, 1600',
            'long': 'This is useful for non e-ink devices.',
            'default': '600',
        },
    }

    def __init__(self, *args, **kwargs):
        BasicNewsRecipe.__init__(self, *args, **kwargs)
        d = self.recipe_specific_options.get('days')
        if d and isinstance(d, str):
            self.oldest_article = float(d)

    feeds = [
        'https://indianexpress.com/section/opinion/feed',
        'https://indianexpress.com/section/delhi-confidential/feed',
        'https://indianexpress.com/section/india/feed',
        'https://indianexpress.com/section/political-pulse/feed',
        'https://indianexpress.com/section/explained/feed',
        'https://indianexpress.com/section/business/feed/',
        'https://indianexpress.com/section/upsc-current-affairs/feed',
        'https://indianexpress.com/section/express-sunday-eye/feed',
        'http://indianexpress.com/section/world/feed',
        'https://indianexpress.com/section/technology/feed',
        'https://indianexpress.com/section/entertainment/feed',
        'https://indianexpress.com/feed',
    ]

    def get_cover_url(self):
        soup = self.index_to_soup(
            'https://www.readwhere.com/newspaper/indian-express/Nagpur/38726'
        )
        citem = soup.find('meta', attrs={'property': 'og:image'})
        return citem['content'].replace('300', '600')

    def preprocess_html(self, soup):
        width = '600'
        w = self.recipe_specific_options.get('res')
        if w and isinstance(w, str):
            width = w
        if h2 := (soup.find(attrs={'itemprop': 'description'}) or soup.find(**classes('synopsis top-description'))):
            h2.name = 'p'
            h2['id'] = 'sub-d'
        for span in soup.findAll(
            'span', attrs={'class': ['ie-custom-caption', 'custom-caption']}
        ):
            span['id'] = 'img-cap'
        for img in soup.findAll('img', attrs={'data-src': True}):
            img['src'] = img['data-src'].split('?')[0] + '?w=' + width
        # if span := soup.find('span', content=True, attrs={'itemprop': 'dateModified'}):
            # date = parse_date(span['content']).replace(tzinfo=None)
            # today = datetime.now()
            # if (today - date) > timedelta(self.oldest_article):
            #     self.abort_article('Skipping old article')
        for img in soup.findAll('img', attrs={'src': True}):
            img['src'] = img['src'].split('?')[0] + '?w=' + width
        return soup
